package cn.donting.web.desktop.core.servlet;


import cn.donting.web.desktop.core.Application;
import cn.donting.web.desktop.servlet.ThreadContext;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

import static cn.donting.web.desktop.core.app.AppGetting.REQUEST_APP_ID;

/**
 * app ID 过滤器
 * 优先级 Parameter--> Attribute--> Header
 * FORWARD 时可以指定  Parameter 来跳转App
 * appId=null 默认为sys
 * 配合DefaultAppGetting 使用
 * @see cn.donting.web.desktop.core.app.DefaultAppGetting
 */
//@WebFilter(filterName = "AppIdFilter", urlPatterns = "/*",dispatcherTypes={DispatcherType.FORWARD})
@Slf4j
public class AppIdFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String appId = httpServletRequest.getParameter("appId");
        if (appId == null) {
            appId = httpServletRequest.getHeader("appId");
        }
        if(appId==null){
            appId= (String) request.getAttribute(REQUEST_APP_ID);
        }
        setAppID(appId,request);
        chain.doFilter(request,response);
    }

    /**
     * 设置 appId 到 Attribute
     * appId==null 默认 sys
     * @param appId
     * @param request
     */
    private void setAppID(String appId,ServletRequest request){
        if(appId==null){
            appId= Application.sysAppId.toString();
        }
        ThreadContext.setAppId(Long.parseLong(appId));
        request.setAttribute(REQUEST_APP_ID,appId);
    }
}
